const app = getApp();
const { module } = app.siteInfo;
const _util = require('../util.js');
const recorderManager = wx.getRecorderManager();
const { getUserInfo } = require('../../../utils/ws/wsxcx-opendata-sdk');

Page({
  data: {
    existCard: {},
    wxInfo: {},
    // avatarUrl: '',
    defaultAvatar: './img/default-avatar.png',
    recordAction: 'new',
    recordTime: '00:00:00',
    recordTips: '录制你的个性语音简介',
    tick: 0,
    imagesCount: 9,
    isWXWork: app.isWXWork,
    showGetUserInfo: false,
    labelAlias: {},
    showExtra: module !== 'ws_training_education' && module.indexOf('ws_micro_shop') === -1,
    isLoaded: false,
    goback:'', //根据上一个页面提供的不同的路径返回某一页面
    qrcodes:[]
  },

  // 兼容不同模块的登录方法
  onLoad: function (options) {
    let that = this;
    console.log("========options=====", options)
    if (options && options.goback){
      that.setData({
        goback: options.goback
      })
    }
    _util.loginBeforeGetMobile().then(res => {
      if (res) {
        let openID = res;
        that.setData({ openID });
        if (options.type == 'import' && this.data.isWXWork){
          that.getEmployeeInfo();
        }else{
        that.checkCard(openID);
        }
        that.onUpdateUserInfo(openID);
        that.getLabelAlias();
      } else {
        wx.showToast({
          title: '登录失败，请退出重试',
          icon: 'none',
        });
      }
    });
  },

  onShow: function () {
    let resPic = wx.getStorageSync('resPic');
    typeof resPic === 'string' && resPic !== '' && this.setData({ customBg: resPic });
  },

  onReady: function () {
    this.recordHandler();
  },

  onHide: function () {
    this.stopTime();
    this.setData({ recordTips: '可重新录制', recordAction: 'new', recordTime: '00:00:00', tick: 0 });

  },

  onUnload: function () {
    this.stopTime();
    this.setData({ recordTips: '可重新录制', recordAction: 'new', recordTime: '00:00:00', tick: 0 });
    wx.setStorageSync('resPic','');
  },

  checkAuth() {
    getUserInfo()
      .then(() => {
      })
      .catch(res => {
        this.setData({
          showGetUserInfo: true,
        });
      });
  },

  // 调起照相机应用
  takePhoto() {
    wx.showModal({
      title: '提示',
      content: '您还没有名片，快速录入制作名片',
      showCancel: true,
      cancelText: '拍照录入',
      cancelColor: '#000000',
      confirmText: '手动录入',
      confirmColor: '#3CC51F',
      success: res => {
        if (res.cancel) app.util.navigateTo('/common/component/universal-card/pages/camera', {}, true);
      },
    });
  },

  // 获取企业员工信息
  getEmployeeInfo(){
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    app.util.request({
      url:'card/index/getWeworkUserInfo',
      data:{
        openid, 
      },
      success: res => {
        console.log("=======getWeworkUserInfo=======", res)
        if (res.data.errno == 0){
          if (res.data.errmsg == '用户未关联企微'){
            wx.showToast({
              title: res.data.errmsg,
              icon: 'none'
            })
            setTimeout(()=>{
              this.checkCard(openid);
            },2000)
          } else {
            console.log(res.data.data);
            let { name = '', avatar = '', email = '', position= ''} = res.data.data
            let existCard = {
              name,
              bg_img: avatar,
              email,
              position,
            }
            this.setData({
              existCard,
              customBg: avatar,
            })
          }
        }
      }
    })
  },

  // 检查用户是否有名片
  checkCard(openid) {
    let that = this;
    let {qrcodes} = this.data;
    app.util.request({
      url: 'card/api/have_cared',
      data: {
        openid,
      },
      cachetime: 0,
      showLoading: true,
      success: function (res) {
        if (Number(res.data.errno) === 0) {
          app.util.request({
            url: 'card/api/get_card_detail',
            data: { openid, get_type: 'edit' },
            success: function (res) {
              if (Number(res.data.errno) === 0) {
                const existCard = res.data.data;
                existCard.images = (existCard.images || []).filter(v => v);
                if(existCard.welcome_pic){
                  qrcodes[0] = existCard.welcome_pic
                }
                that.setData({  
                  existCard,
                  // avatarUrl: existCard.avatar,
                  customBg: existCard.bg_img,
                  // haveCard: res.data,
                  recordTips: existCard.audio && existCard.audio !== 'undefined' ? '重新录制' : that.data.recordTips,
                  qrcodes
                });
              } else {
                that.takePhoto();
              }
            },
          });
        } else {
          that.takePhoto();
        }
      },
      fail: function (res) {
        that.takePhoto();
      },
    });
  },

  // 获取地址
  getLocation(e) {
    const that = this;
    let { existCard } = this.data;

    wx.chooseLocation({
      success: function (res) {
        existCard.address = res.address;
        that.setData({
          existCard,
          latitude: res.latitude,
          longitude: res.longitude,
        });
      },
    });
  },

  // 更新用户信息至后端
  onUpdateUserInfo(openid, name) {
    // const data = e.detail;
    // const { openid } = this.data;

    app.util.request({
      url: 'card/api/up_user_info',
      data: {
        openid,
        // nickname: name,
        // avatar,
      },
      cachetime: 0,
    });

    // if (data.errMsg === 'getUserInfo:ok') {
    //   const { avatarUrl: avatar, nickName: nickname } = data.userInfo;
    //   this.setData({
    //     wxInfo: data.userInfo,
    //     avatarUrl: data.userInfo.avatarUrl,
    //   });
    // }
  },

  getLabelAlias() {
    app.util.request({
      url: 'card/api/aliasList',
      showLoading: true,
      success: res => {
        if (res.data && res.data.errno === 0) {
          const data = res.data.data;
          this.setData({ labelAlias: data });
        }
      },
      complete: () => {
        this.setData({
          isLoaded: true
        })
      }
    });
  },

  // 验证并提交表单
  formSubmit(e) {
    const that = this;
    const { name = '', company = '', position = '', mobile = '', email = '', address = '', wechatId = '', signature = '' } = e.detail.value;
    let { openID, latitude, longitude, customBg, audioDuration, audioUrl, cardPictures, qrcodes = [],existCard: { images: oldImg, welcome_msg }, labelAlias,  } = this.data;
    if (!name || !name.trim()) {
      wx.showToast({
        title: '请填写姓名',
        icon: 'none',
      });
      return false;
    } else if (name.length > 5) {
      wx.showToast({
        title: '名字过长,仅限5个字',
        icon: 'none',
      });
      return false;
    }


    if (!company && labelAlias.iscompany !== '0' || !company.trim()) {
      wx.showToast({
        title: '请填写公司名称',
        icon: 'none',
      });
      return;
    }
    if (!position && labelAlias.isposition !== '0' || !position.trim()) {
      wx.showToast({
        title: '请填写职位',
        icon: 'none',
      });
      return;
    }

    if (!mobile || !mobile.trim()) {
      wx.showToast({
        title: '请填写手机号',
        icon: 'none',
      });
      return false;
    } else {
      const exp = app.util.phoneExp.mobile;
      if (!exp.test(mobile)) {
        wx.showToast({ title: '手机号格式错误', icon: 'none' });
        return false;
      }
    }
    
    if (email){
      const myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
      if (!myReg.test(email)) {
        wx.showToast({ title: '邮箱格式错误', icon: 'none' });
        return false;
      }
    }

    if (!latitude || !longitude) {
      ({ latitude, longitude } = this.data.existCard);
    }

    if (!customBg) {
      customBg = this.data.existCard.bg_img;
    }
    app.util.request({
      url: 'card/api/add_card',
      data: {
        openid: openID,
        name,
        company,
        position,
        mobile,
        email,
        address,
        signature,
        latitude,
        longitude,
        wechatId,
        bg_img: customBg || '',
        audio: audioUrl || this.data.existCard.audio,
        audioDuration: audioDuration || this.data.existCard.audioDuration,
        images: cardPictures ? cardPictures.join(',') : (oldImg ? oldImg.join(',') : ''),
        welcome_msg: welcome_msg || '',
        welcome_pic: qrcodes[0] || ''
      },
      success: function (res) {
        if (Number(res.data.errno) === 0) {
          wx.showToast({
            title: '保存成功',
            duration: 2000,
          });
          setTimeout(function () {
            // 判断上一页是card-preview的话，返回上一页，而不是打开新页面
            let pages = getCurrentPages() || [];
            // && pages[pages.length - 2].route === 'common/component/universal-card/card-preview'
            if (pages[pages.length - 2] && (pages[pages.length - 2].route === 'common/component/universal-card/card-preview' || pages[pages.length - 2].route === 'common/component/universal-card/card-show')) {
              wx.navigateBack({ delta: 1 });
            }
            else {
              if(that.data.goback){
                app.util.navigateTo(that.data.goback, {}, true);
              }else{
                app.util.navigateTo('common/component/universal-card/card-preview', {}, true);
              }
            }
          }, 500);
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          })
        }
      },
    });
  },

  // 获取地址返回后，原来填写的数据会清空，所以保存一下。
  saveInput(e) {
    let { existCard } = this.data;
    const value = e.detail.value;
    const flag = e.currentTarget.dataset.flag;
    existCard[flag] = value;
    this.setData({ existCard });
  },

  // 获取手机号码。
  getMobile(e) {
    let encryptedData = e.detail.encryptedData;
    let iv = e.detail.iv;
    if (encryptedData && iv) {
      this.requestMobile(e);
    } else {
      wx.showToast({
        title: '已取消或失败',
        duration: 1500,
        icon: 'none',
      });
    }
  },

  requestMobile(e) {
    let that = this;
    const { openID } = this.data;
    app.util.request({
      url: 'card/api/get_phone_number',
      data: { encryptedData: e.detail.encryptedData, iv: e.detail.iv, openid: openID },
      method: 'POST',
      catchtime: 0,
      success: function (res) {
        const mobile = res.data.data.phoneNumber || '';
        if (mobile !== '') {
          that.setData({
            mobile,
            existCard: { ...that.data.existCard, mobile },
          });
        } else {
          wx.showToast({
            title: '手机号获取失败',
            duration: 1500,
            icon: 'none',
          });
        }
      },
    });
  },

  // 自定义背景图片
  changeBg() {
    // const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({
          title: '加载中',
          mask: false,
        });
        let tempFilePaths = res.tempFilePaths;
        let url = 'utility/file/upload';
        if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
          url = app.util.url(url, { type: 'image', thumb: '0' });
        }

        wx.setStorage({
          key: 'uploadUrl',
          data: url,
        });
        // card
        wx.hideLoading();
        app.util.navigateTo(`/common/component/cropper/cropper?sceneName=card&src=${tempFilePaths[0]}`);
      },
    });
  },

  showTime() {
    let { recordTime: time, tick } = this.data;
    let [h, m, s] = time.split(':').map(item => Number(item));
    let interval = setInterval(() => {
      tick += 1;
      s = tick < 60 ? tick : tick % 60;
      m = tick < 60 ? 0 : (Math.floor(tick / 60) < 60 ? Math.floor(tick / 60) : tick % 60);
      h = tick < 3600 ? 0 : tick % 3600;
      time = `${double(h)}:${double(m)}:${double(s)}`;
      this.setData({ recordTime: time, tick });
    }, 1000);
    this.setData({ interval });
    const double = (n) => { return n < 10 ? '0' + n : n };
  },

  stopTime() {
    clearInterval(this.data.interval);
  },

  // 录音处理
  recordHandler(e) {
    recorderManager.onStart(() => {
      this.setData({ recordAction: 'pause', recordTips: '开始：' }, () => {
        this.showTime();
      });
    });

    recorderManager.onPause(() => {
      this.setData({ recordAction: 'resume', recordTips: '暂停：' }, () => {
        this.stopTime();
      });
    });

    recorderManager.onResume(() => {
      this.setData({ recordAction: 'pause', recordTips: '开始：' }, () => {
        this.showTime();
      });
    });

    recorderManager.onStop((res) => {
      this.setData({ recordAction: 'done', recordTips: '完成，录制时长：' }, () => {
        this.stopTime();
        setTimeout(() => {
          this.setData({ recordTips: '可重新录制', recordAction: 'new', recordTime: '00:00:00', tick: 0 });
        }, 2000);
      });
      this.uploadAudio(res.tempFilePath, res.duration);
    });
  },

  recordStart() {
    const options = {
      duration: 50000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50,
    };
    recorderManager.start(options);
  },

  recordPause() {
    recorderManager.pause();
    this.setData({});
  },

  recordResume() {
    recorderManager.resume();
    this.setData({});
  },

  recordStop() {
    recorderManager.stop();
  },

  uploadAudio(file, time) {
    let url = `${app.util.url('utility/file/upload')}type=audio`;
    wx.uploadFile({
      url,
      filePath: file,
      formData: { time },
      name: 'file',
      success: (res) => {
        this.setData({ audioUrl: JSON.parse(res.data).url || '', audioDuration: time || 0 });
      },
    });
  },

  uploadPicturesEvent(e) {
    let existCard = this.data.existCard;
    existCard.images = e.detail.mine_program_thumb;
    this.setData({ cardPictures: e.detail.mine_program_thumb, existCard });
  },

  uploadCodeEvent(e){
    let existCard = this.data.existCard;
    existCard.welcome_pic = e.detail.mine_program_thumb;
    this.setData({ qrcodes: e.detail.mine_program_thumb, existCard });
  },
});